package day03;
//实现分数类，完成1/1+1/2+....+1/20的精确值
public class Fraction {
    public static void main(String[] args) {
        Fraction a = new Fraction(1, 1);
        System.out.print(a.toString());

        for (int i=2;i<=20;i++) {//循环计算
            Fraction b = new Fraction(1, i);
            System.out.print("+"+b);
            a = a.add(a,b);
        }
        System.out.println("\n"+a);
    }

    Fraction add(Fraction a,Fraction b) {
        Fraction c = new Fraction();
        c.up = a.up * b.down + a.down * b.up;
        c.down = a.down * b.down;
        double g = gcd(c.up, c.down);//化简
        c.up /= g;
        c.down /= g;
        return c;
    }
    double up, down;
    @Override
    public String toString() {
        return String.format("%.0f/%.0f", this.up, this.down);
    }
    public Fraction(double up, double down) {
        double g = gcd(up, down);
        up /= g;
        down /= g;
        this.up = up;
        this.down = down;
    }

    public Fraction() {
        this(0, 1);
    }

    static double gcd(double a, double b) {//最大公约数
        return b == 0 ? a : gcd(b, a % b);
    }
}
